axios.defaults.baseURL = "http://cba.itlike.com/public/index.php?s=/api/";
let strMenu = "";
const menu = document.querySelector(".menu");
const goods = document.querySelector(".goods ul");
let flag = true;
const noGood = document.querySelector(".noGood");

function getData(index) {
  axios.get("/category/list").then((res) => {
    if (res.status === 200) {
      console.log();
      let {
        data: {
          data: { list },
        },
      } = res;
      if (flag) {
        getMenu(list);
        flag = false;
      }
      getGoods(list[index].children);
    }
  });
}
getData(0);

//商品菜单函数
function getMenu(arr2) {
  arr2.forEach((item, index) => {
    strMenu += `
      <a href="javascript:;" data-index=${index}>${item.name}</a>
    `;
  });
  menu.innerHTML = strMenu;

  //菜单第一个高亮显示
  document.querySelectorAll(".menu a")[0].classList.add("cur");
}

//商品详情函数
function getGoods(arr) {
  if (arr === undefined) {
    noGood.style.display = "block";
    goods.innerHTML = "";
    return;
  }
  noGood.style.display = "none";
  goods.innerHTML = arr
    .map((item) => {
      console.log(item.category_id);
      return `
      <li>
        <div>
          <a href="list.html?category_id=${item.category_id}">
            <img src="${item.image.preview_url}" alt=""/>
          </a>
        </div>
        <p>${item.name}</p>
      </li>
    `;
    })
    .join("");
}

//点击菜单高亮显示
menu.addEventListener("click", function (e) {
  const target = e.target;
  if (target.tagName === "A") {
    let index = target.dataset.index;
    let isActive = document.querySelector(".menu .cur");
    isActive && document.querySelector(".menu .cur").classList.remove("cur");
    target.classList.add("cur");

    getData(index);
  }
});
